<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鲜时蔬 - 用户注册</title>
    <!-- 核心依赖：保持与首页一致的组件库引入 -->
    <script src="../../js/vue.js"></script>
    <link rel="stylesheet" href="../../css/index.css">
    <script src="../../js/index.js"></script>
    <script src="../../js/axios.min.js"></script>

    <!-- 基础样式：延续品牌绿色主题，优化表单布局 -->
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            min-height: 100vh;
            padding-top: 80px; /* 为顶部导航栏留空间 */
            padding-bottom: 50px;
        }

        /* 导航栏：复用首页导航样式，确保风格统一 */
        .header {
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .container {
            width: 1140px;
            margin: 0 auto;
            padding: 0 15px;
        }

        @media (max-width: 1199px) { .container { width: 960px; } }
        @media (max-width: 991px) { .container { width: 720px; } }
        @media (max-width: 767px) { .container { width: 100%; } }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            color: #27ae60;
            text-decoration: none;
        }

        .logo i { margin-right: 8px; }

        .nav { display: flex; }

        .nav a {
            margin: 0 15px;
            text-decoration: none;
            color: #666;
            font-size: 14px;
            padding: 5px 0;
        }

        .nav a.active {
            color: #27ae60;
            border-bottom: 2px solid #27ae60;
        }

        .user-actions { display: flex; align-items: center; }

        .user-actions button {
            margin-left: 15px;
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
        }

        .user-actions button i { margin-right: 5px; }

        /* 主内容区：居中显示注册表单，增强视觉聚焦 */
        .main {
            padding: 40px 0;
        }

        /* 注册表单容器：卡片式设计，带阴影提升层次感 */
        .register-container {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 30px;
            max-width: 800px;
            margin: 0 auto;
        }

        /* 注册标题：底部绿色下划线，强化品牌识别 */
        .register-title {
            text-align: center;
            margin-bottom: 30px;
        }

        .register-title h2 {
            font-size: 24px;
            color: #333;
            display: inline-block;
            padding-bottom: 10px;
            border-bottom: 2px solid #27ae60;
        }

        /* 表单布局：分栏适配，移动端自动堆叠 */
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        @media (max-width: 767px) {
            .form-row {
                flex-direction: column; /* 移动端垂直排列 */
                gap: 0;
            }
        }

        /* 表单项：统一间距和样式 */
        .el-form-item {
            margin-bottom: 20px;
            flex: 1; /* 分栏时自动占满剩余空间 */
        }

        /* 输入框样式：聚焦时显示品牌绿色边框 */
        .el-input, .el-select {
            width: 100%;
            border-radius: 4px !important;
            border: 1px solid #e5e7eb !important;
            transition: all 0.3s ease;
        }

        .el-input:hover, .el-select:hover {
            border-color: #27ae60 !important;
            box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.1) !important;
        }

        .el-input:focus-within, .el-select:focus-within {
            border-color: #27ae60 !important;
            box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.2) !important;
        }

        /* 验证码容器样式 */
        .captcha-container {
            display: flex;
            gap: 10px;
        }

        .captcha-input {
            flex: 1;
        }

        .captcha-btn {
            width: 120px;
            background-color: #27ae60 !important;
            color: white !important;
            border: none !important;
        }

        .captcha-btn:disabled {
            background-color: #cccccc !important;
            cursor: not-allowed;
        }

        /* 上传组件：适配表单风格 */
        .el-upload--picture-card {
            width: 100%;
            height: 180px;
            border-radius: 4px;
        }

        .el-upload-list--picture-card .el-upload-list__item {
            width: 100%;
            height: 180px;
        }

        /* 注册按钮：品牌绿色背景，悬停效果 */
        .submit-btn {
            width: 100%;
            height: 44px;
            background-color: #27ae60 !important;
            border: none !important;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .submit-btn:hover {
            background-color: #219d5d !important;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(39, 174, 96, 0.2);
        }

        /* 表单说明文字：灰色小字，提升用户引导 */
        .form-desc {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
        }

        /* 已有账号提示：居中显示，与表单底部间距 */
        .login-tip {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
        }

        .login-tip a {
            color: #27ae60;
            text-decoration: none;
            margin-left: 5px;
        }

        .login-tip a:hover {
            text-decoration: underline;
        }

        /* 页脚：复用首页样式，保持页面完整性 */
        .footer {
            background: #333;
            color: #fff;
            padding: 30px 0;
            margin-top: 50px;
        }

        .footer-content {
            text-align: center;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 导航栏：与首页一致，保持风格统一 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <button @click="goToUserLogin">
                        <i class="el-icon-user"></i> 用户登录
                    </button>
                    <button @click="goToCart">
                        <i class="el-icon-shopping-cart"></i> 购物车
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区：用户注册表单 -->
    <main class="main">
        <div class="container">
            <div class="register-container">
                <!-- 注册标题 -->
                <div class="register-title">
                    <h2>用户注册</h2>
                </div>

                <!-- 注册表单：带验证规则，分多部分信息填写 -->
                <el-form :model="registerForm" ref="registerForm" :rules="registerRules" label-width="120px">
                    <!-- 第一部分：账号信息（用户登录用） -->
                    <el-form-item label="用户昵称" prop="nickName">
                        <el-input
                                v-model="registerForm.nickName"
                                placeholder="请设置用户昵称（6-20位字母/数字）"
                                @keyup.enter.native="handleRegister">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="登录账号" prop="userName">
                        <el-input
                                v-model="registerForm.userName"
                                placeholder="请设置登录账号（6-20位字母/数字）"
                                @keyup.enter.native="handleRegister">
                        </el-input>
                    </el-form-item>

                    <div class="form-row">
                        <el-form-item label="登录密码" prop="password">
                            <el-input
                                    v-model="registerForm.password"
                                    type="password"
                                    placeholder="请设置密码（6-20位，含字母和数字）"
                                    @keyup.enter.native="handleRegister">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input
                                    v-model="registerForm.confirmPassword"
                                    type="password"
                                    placeholder="请再次输入密码"
                                    @keyup.enter.native="handleRegister">
                            </el-input>
                        </el-form-item>
                    </div>

                    <el-form-item label="联系电话" prop="phonenumber">
                        <el-input
                                v-model="registerForm.phonenumber"
                                placeholder="请输入商家联系电话"
                                @keyup.enter.native="handleRegister">
                        </el-input>
                        <div class="form-desc">用于接收验证码和账号通知</div>
                    </el-form-item>

                    <!-- 验证码部分 -->
                    <el-form-item label="验证码" prop="captcha" required>
                        <div class="captcha-container">
                            <el-input
                                    v-model="registerForm.captcha"
                                    placeholder="请输入验证码"
                                    class="captcha-input"
                                    maxlength="4"
                                    @keyup.enter.native="handleRegister">
                            </el-input>
                            <el-button
                                    :disabled="countdown > 0"
                                    @click="getCaptcha"
                                    class="captcha-btn">
                                {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                            </el-button>
                        </div>
                    </el-form-item>

                    <el-form-item label="电子邮箱" prop="email">
                        <el-input
                                v-model="registerForm.email"
                                placeholder="请输入电子邮箱"
                                @keyup.enter.native="handleRegister">
                        </el-input>
                        <div class="form-desc">用于接收重要通知等</div>
                    </el-form-item>

                    <el-form-item label="用户性别" prop="sex">
                        <el-select
                                v-model="registerForm.sex"
                                placeholder="请选择用户性别">
                            <el-option label="男" value="0"></el-option>
                            <el-option label="女" value="1"></el-option>
                            <el-option label="未知" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="头像上传" prop="avatar">
                        <el-upload
                                action="/vegetablemarketexpress/user/uploadAvatarImage"
                                name="pic"
                                list-type="picture-card"
                                :on-success="handleAvatarUpload"
                                :on-error="handleUploadError"
                                :file-list="avatarFileList"
                                :before-upload="beforeAvatarUpload"
                        >
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <div class="form-desc">请上传头像图片（支持JPG/PNG格式，大小不超过2MB）</div>
                    </el-form-item>
                    <!-- 注册提交按钮 -->
                    <el-form-item>
                        <el-button
                                type="primary"
                                class="submit-btn"
                                @click="handleRegister"
                                :loading="loading">
                            提交注册
                        </el-button>
                    </el-form-item>
                    <!-- 已有账号提示 -->
                    <div class="login-tip">
                        已有账号？<a href="#" @click.prevent="goToUserLogin">立即登录</a>
                    </div>
                </el-form>
            </div>
        </div>
    </main>

    <!-- 页脚：与首页一致，保持页面结构完整 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>
</div>

<!-- Vue 逻辑：包含表单验证、验证码发送、文件上传、注册提交等核心功能 -->
<script>
    new Vue({
        el: '#app',
        data() {
            // 密码验证规则：必须包含字母和数字，6-20位
            const validatePassword = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入密码'));
                }
                if (value.length < 6 || value.length > 20) {
                    return callback(new Error('密码长度必须在6-20个字符之间'));
                }
                if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/.test(value)) {
                    return callback(new Error('密码必须包含字母和数字'));
                }
                callback();
            };

            // 确认密码验证：必须与密码一致
            const validateConfirmPassword = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请确认密码'));
                }
                if (value !== this.registerForm.password) {
                    return callback(new Error('两次输入的密码不一致'));
                }
                callback();
            };

            // 手机号验证规则
            const validatePhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入联系电话'));
                }
                if (!/^1[3-9]\d{9}$/.test(value)) {
                    return callback(new Error('请输入有效的手机号码'));
                }
                callback();
            };

            // 验证码验证规则
            const validateCaptcha = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入验证码'));
                }
                if (!/^\d{4}$/.test(value)) {
                    return callback(new Error('验证码必须是4位数字'));
                }
                callback();
            };

            // 邮箱验证规则
            const validateEmail = (rule, value, callback) => {
                if (!value) {
                    return callback(); // 邮箱非必填
                }
                if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
                    return callback(new Error('请输入有效的电子邮箱'));
                }
                callback();
            };
            // 性别验证规则
            const validateSex = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请选择用户性别'));
                }
                callback();
            };

            return {
                // 初始化头像文件列表
                avatarFileList: [],
                // 商家注册表单数据
                registerForm: {
                    nickName: '',      // 用户姓名或昵称
                    userName: '',    // 登录账号
                    email: '',         // 用户邮箱
                    phonenumber: '',   // 手机号码
                    sex: '',           // 用户性别(0男 1女 2未知)
                    avatar: '',        // 头像路径 存储后端返回的本地访问路径（如：/uploads/avatar/20240910/xxx.jpg）
                    password: '',           // 登录密码
                    confirmPassword: '',    // 确认密码
                    captcha: ''             // 验证码
                },
                loading: false,              // 提交按钮加载状态
                countdown: 0,                // 验证码倒计时（秒）

                // 表单验证规则
                registerRules: {
                    nickName: [
                        { required: true, message: '请输入用户昵称', trigger: 'blur' },
                        { min: 2, max: 20, message: '用户昵称长度必须在2-20个字符之间', trigger: 'blur' }
                    ],
                    userName: [
                        { required: true, message: '请输入登录账号', trigger: 'blur' },
                        { min: 6, max: 20, message: '登录账号长度必须在6-20个字符之间', trigger: 'blur' },
                        { pattern: /^[a-zA-Z0-9]+$/, message: '登录账号只能包含字母和数字', trigger: 'blur'}
                    ],
                    password: [
                        { required: true, validator: validatePassword, trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
                    ],
                    phonenumber: [
                        { required: true, validator: validatePhone, trigger: 'blur' }
                    ],
                    captcha: [
                        { required: true, validator: validateCaptcha, trigger: 'blur' }
                    ],
                    email: [
                        { validator: validateEmail, trigger: 'blur' }
                    ],
                    sex: [
                        { required: true, validator: validateSex, trigger: 'change' }
                    ],
                    avatar: [
                        { required: false, message: '请上传头像', trigger: 'change' } // 头像非必填，可根据需求调整为必填
                    ]
                }
            };
        },
        methods: {
            // 跳转到用户登录页
            goToUserLogin() {
                window.location.href = '/vegetablemarketexpress/html/front/login.html';
            },

            // 跳转到购物车页面
            goToCart() {
                window.location.href = 'cart.html';
            },

            // 获取验证码
            getCaptcha() {
                const _this = this;

                // 调用后端验证码接口
                axios.get('/vegetablemarketexpress/user/registerCaptcha')
                    .then(response => {
                        if (response.data.code === 200) {
                            // 显示验证码
                            _this.$message.success('验证码获取成功');

                            // 开始倒计时
                            _this.countdown = 60;
                            const timer = setInterval(() => {
                                _this.countdown--;
                                if (_this.countdown <= 0) {
                                    clearInterval(timer);
                                }
                            }, 1000);
                        } else {
                            _this.$message.error(response.data.message || '验证码获取失败');
                        }
                    })
                    .catch(error => {
                        console.error('验证码获取错误:', error);
                        _this.$message.error('验证码获取异常，请检查网络');
                    });
            },

            // 头像上传前验证（格式+大小）
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2; // 限制2MB以内

                if (!isJPG) {
                    this.$message.error('只能上传JPG/PNG格式的头像图片');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('头像图片大小不能超过2MB');
                    return false;
                }
                return true;
            },

            // 头像上传成功处理（存储头像URL到表单）
            handleAvatarUpload(response, file, fileList) {
                if (response.code === 200) {
                    // 后端返回 {filePath: "图片地址", originName: "原文件名"}
                    this.registerForm.avatar = response.data.filePath;
                    this.avatarFileList = [{
                        name: 'avatar.jpg',
                        url: response.data.filePath
                    }];
                    this.$message.success('头像上传成功');
                } else {
                    this.$message.error(response.message || '头像上传失败，请重试');
                }
            },

            // 上传失败通用处理
            handleUploadError(err) {
                console.error('文件上传失败:', err);
                this.$message.error('网络异常，头像上传失败');
            },

            // 提交注册表单
            handleRegister() {
                // 1. 表单验证
                this.$refs.registerForm.validate((valid) => {
                    if (valid) {
                        this.loading = true; // 开启加载状态，防止重复提交

                        // 2. 构造请求参数（移除confirmPassword，避免冗余传参）
                        const registerParams = { ...this.registerForm };
                        delete registerParams.confirmPassword;

                        // 3. 调用后端注册接口，将验证码作为参数传递
                        axios.post('/vegetablemarketexpress/user/registerUser?captcha=' + encodeURIComponent(this.registerForm.captcha), registerParams)
                            .then(response => {
                                this.loading = false; // 关闭加载状态

                                // 4. 处理接口响应
                                if (response.data.code === 200) {
                                    this.$message.success('注册成功，即将跳转登录页');
                                    // 延迟1.5秒跳转，给用户看成功提示
                                    setTimeout(() => {
                                        this.goToUserLogin();
                                    }, 1500);
                                } else {
                                    // 后端返回的错误信息（如账号已存在、手机号已注册等）
                                    this.$message.error(response.data.message || '注册失败，请重试');
                                }
                            })
                            .catch(error => {
                                this.loading = false; // 异常时也要关闭加载状态
                                console.error('用户注册请求失败:', error);

                                if (error.response && error.response.data) {
                                    this.$message.error(error.response.data.message || '注册失败');
                                } else {
                                    this.$message.error('网络异常，注册请求发送失败');
                                }
                            });
                    }
                });
            }
        }
    });
</script>
</body>
</html>